var crypto = require('crypto');
var RUtil = require('./dataformatUtil');
var apinfo = require('../models/apinfo');
var config = require('../config');
var sd = require('silly-datetime');
var iconv = require('iconv-lite');
// 加载编码转换模块
///////////////////////////////////////////////
var fs=require('fs');
var splitstr='${sp}';
var companyname="dy";
///////////////////////////////////////////////
var sd = require('silly-datetime');
var apbi_filetype="apbi";
var apbi_index=1;
var shxx_filetype="shxx";
var shxx_index=1;
var xnsf_filetype="xnsf";
var xnsf_index=1;
var heartbeat_filetype="sbqcxx";
var heartbeat_index=1;
var apbi_outputpath = config['apbi_outputpath'];
var shxx_outputpath = config['shxx_outputpath'];
var xnsf_outputpath = config['xnsf_outputpath'];
var sbqcxx_outputpath = config['sbqcxx_outputpath'];
var currentdate="";
///////////////////////////////////////////////
var apbi_filename="";
var xnsf_filename="";
var shxx_filename="";
var heartbeat_filename="";

var apbi_filename_old="";
var xnsf_filename_old="";
var shxx_filename_old="";
var heartbeat_filename_old="";
var writeStream_apbi=null,writeStream_xnsf=null,writeStream_shxx=null, writeStream_heartbeat=null;
var oldinterval=config['generateinterval'];
global.setinterval=config['generateinterval'];
var schedule = require("node-schedule");
var rule     = new schedule.RecurrenceRule();
var times = [];
for(var i=0; i<60; i+= parseInt( oldinterval)){
    times.push(i);
}
rule.second  = times;
///////////////////////////////////////////////
var heartbeatschedule = require("node-schedule");
var heartbeatrule     = new heartbeatschedule.RecurrenceRule();
var heartbeattimes = [];
var heartbeatinterval=1;
for(var i=0; i<60; i++){
    heartbeattimes.push(i);
}
heartbeatrule.minute  = heartbeattimes;
///////////////////////////////////////////////
var job=null;

exports.setinterval = function(req,rsp){
    var tmpint=parseInt(req.query.interval);
    if(tmpint>=5 && tmpint <60){
        global.setinterval=tmpint;
        rsp.send({status:true});
        rsp.end();
    }
    else{
        rsp.send({status:false, msg:'interval too shot. valid interval: 5-59'});
        rsp.end();
    }
}

exports.process = function( server ){
    try{
        if (!fs.existsSync(apbi_outputpath)) {
            fs.mkdirSync(apbi_outputpath);
        }
        if (!fs.existsSync(xnsf_outputpath)) {
            fs.mkdirSync(xnsf_outputpath);
        }
        if (!fs.existsSync(shxx_outputpath)) {
            fs.mkdirSync(shxx_outputpath);
        }
        if (!fs.existsSync(sbqcxx_outputpath)) {
            fs.mkdirSync(sbqcxx_outputpath);
        }
        processMsg(server);
    }
    catch(e){
        console.log("err: "+e);
    }
};

function setHeartbeatFilePath(isfirst){
    currenttime=sd.format(new Date(), 'YYYYMMDDHHmmss');
    heartbeat_filename_old=heartbeat_filename;
    heartbeat_filename=sbqcxx_outputpath + "WIFI-"+currenttime+"-"+heartbeat_filetype+"-"+companyname +".dat";
    if(writeStream_heartbeat!=null){writeStream_heartbeat.end();}
    writeStream_heartbeat = fs.createWriteStream(heartbeat_filename);
}

function setFilePath(isfirst){
    currenttime=sd.format(new Date(), 'YYYYMMDDHHmmss');
    apbi_filename_old=apbi_filename;
    xnsf_filename_old=xnsf_filename;
    shxx_filename_old=shxx_filename;
    apbi_filename=apbi_outputpath + "WIFI-"+currenttime+"-"+apbi_filetype+"-"+companyname +".dat";
    xnsf_filename=xnsf_outputpath + "WIFI-"+currenttime+"-"+xnsf_filetype+"-"+companyname +".dat";
    shxx_filename=shxx_outputpath + "WIFI-"+currenttime+"-"+shxx_filetype+"-"+companyname +".dat";
    if(writeStream_apbi!=null){writeStream_apbi.end();}
    if(writeStream_xnsf!=null){writeStream_xnsf.end();}
    if(writeStream_shxx!=null){writeStream_shxx.end();}
    writeStream_apbi = fs.createWriteStream(apbi_filename);
    writeStream_xnsf = fs.createWriteStream(xnsf_filename);
    writeStream_shxx = fs.createWriteStream(shxx_filename);
}

function clearEmptyFile(filename){
    try{
        var states="";
        if(filename!=""){
            states = fs.statSync(filename);
            if(states.size==0){
                fs.unlinkSync(filename);
            }
        }
    }catch(e){

    }

}

function processMsg(server) {
    var currenttime=sd.format(new Date(), 'YYYYMMDDHHmmss');
    setFilePath(true);
    setHeartbeatFilePath(true);
    
    job = schedule.scheduleJob(rule, function(){
        setFilePath(false);
        clearEmptyFile(apbi_filename_old);
        clearEmptyFile(xnsf_filename_old);
        clearEmptyFile(shxx_filename_old);
    });

    var heartbeatjob = heartbeatschedule.scheduleJob(heartbeatrule, function(){
        setHeartbeatFilePath(false);
        clearEmptyFile(heartbeat_filename_old);
    });

    setInterval(function () {
        if(oldinterval!=global.setinterval){
            console.log('文件生成周期设置生效：由'+oldinterval+"变为"+global.setinterval);
            oldinterval=global.setinterval;
            times = [];
            for(var i=0; i<60; i+=oldinterval){
                times.push(i);
            }
            rule.second  = times;
            if(job!=null){
                job.cancel();
            }
           job = schedule.scheduleJob(rule, function(){
                currenttime=sd.format(new Date(), 'YYYYMMDDHHmmss');
               setFilePath(false);
            });
        }
    }, 5000);


    var io = require('socket.io')(server);
    //socket部分
    io.on('connection', function(socket) {
        //接收并处理客户端的事件
        socket.on(apbi_filetype, function(data) {
            //writeFile(apbi_filename,  data);
            data=data+apbi_index+'\n';
            apbi_index++;
            data=iconv.encode(data, 'gbk');
            writeStream_apbi.write(data);
        });

        socket.on(xnsf_filetype, function(data) {
            //writeFile(xnsf_filename,  data);
            data=data+xnsf_index+'\n';
            xnsf_index++;
            data=iconv.encode(data, 'gbk');
            writeStream_xnsf.write(data);
        });

        socket.on(shxx_filetype, function(data) {
            //writeFile(shxx_filename,  data);
            data=data+shxx_index+'\n';
            shxx_index++;
            data=iconv.encode(data, 'gbk');
            writeStream_shxx.write(data);
        });

        socket.on('heartbeat', function(data) {
            console.log('heartbeat');
            data=data + '\n';
            data=iconv.encode(data, 'gbk');
            writeStream_heartbeat.write(data);
        })

        //断开事件
        socket.on('disconnect', function(data) {
            console.log('client disconnect');

        })

    });
}


function writeFile(file,  recorditem){
    var writeStream = fs.createWriteStream(file);
    writeStream.write(recorditem);
    /*fs.appendFileSync(file, recorditem, function(err){
        if(err)
            console.log("fail " + err);
    });*/
}

function deleteall(path) {
    var files = [];
    if(fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function(file, index) {
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteall(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        //fs.rmdirSync(path);
    }
};

